'use strict';

const Controller = require('egg').Controller;
const fs = require('mz/fs');
const path = require("path")
class DoFormController extends Controller {
    async index() {
        const { ctx } = this;
        // console.log(ctx.request.body);
        // console.log(ctx.request.files[0].filepath);
        var { username, age, sex } = ctx.request.body;
        age = Number(age)
        // console.log(username);
        var filename = ctx.request.files[0].filepath;
        // console.log(filename);
        var reader = fs.createReadStream(filename);
        var uploadFile = `${process.cwd()}/app/public/${path.basename(filename)}`;
        // console.log(uploadFile);
        var write = fs.createWriteStream(uploadFile);
        reader.pipe(write);
        var logo = ctx.origin + "/public/" + path.basename(filename);
        // console.log(logo);
        var db = this.app.mongodb;
        const collection = await db.collection("member");
        // console.log(collection);
        var res = await db.collection("member").find({ username }).toArray();
        if (res.length) {
            ctx.body = "<script>alert('已添加过该成员');location.href='/form'</script>"
        } else {
            await collection.insertOne({ username, age, sex, logo })
            await ctx.redirect("/home")
        }
    }
}

module.exports = DoFormController;
